#include "mutex.hpp"

using namespace std;

#define NUM 4
int tickes = 1000;  // 10张票, 临界资源

class threadData{
public:
    threadData(int number, pthread_mutex_t *_mutex){
        threadName = "thread-" + to_string(number);
        mutex = _mutex;  // 确保各个线程指向同一把锁
    }
    string threadName;
    pthread_mutex_t* mutex;
};

void* threadFunc(void* arg){ 
    threadData* data = (threadData*)arg;
    while(tickes > 0){
        LockGuard lock(data->mutex);  // 临时的LoacGuard   它的构造函数会自动加锁
        // 下一轮循环会析构函数自动解锁        

        if (tickes > 0){
            printf("threadName:%s, have tickes:%d\n", data->threadName.c_str(), tickes);
            usleep(1000);

            tickes --;  // 抢一张票
        }else{
            break;
        }
    }
    return NULL;
}

int main(){
    // 定义一把锁
    pthread_mutex_t mutex;  // 局部锁，如果放到全局，就不用 init和destroy了
    pthread_mutex_init(&mutex, NULL);




    vector<pthread_t> threads;  // 线程数组
    vector<threadData*> threadDatas;  // 线程参数数据
    for(int i = 0; i < NUM; i++){
        threadData* data = new threadData(i, &mutex);
        threadDatas.push_back(data);
        pthread_t thread;
        
        pthread_create(&thread, NULL, threadFunc, (void*)data);
        threads.push_back(thread);
    }


    // 释放资源
    for (auto tid : threads){
        pthread_join(tid, NULL);
    }
    for (auto data : threadDatas){
        delete data;
    }

    pthread_mutex_destroy(&mutex);  // 销毁锁
    return 0;
}